//
//  FPConfirmLoanContractController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/26.
//

#import "FPConfirmLoanContractController.h"
#import "FPLoanModel.h"
#import "FPInreviewController.h"
#import <WebKit/WebKit.h>

@interface FPConfirmLoanContractController () <WKNavigationDelegate , WKUIDelegate>

@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (nonatomic , strong) WKWebView *webView;
@property (nonatomic , strong) UIActivityIndicatorView *loadingView;

@end

@implementation FPConfirmLoanContractController

- (UIActivityIndicatorView *)loadingView {
    
    if (!_loadingView) {
    
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];
        loadingView.hidesWhenStopped = YES;
        [self.view addSubview:_loadingView = loadingView];
//        loadingView.center = self.view.center;
        loadingView.frame = CGRectMake(SCREEN_WIDTH / 2.f - 37.f / 2.f, SCREEN_HEIGHT / 2.f - 37.f / 2.f, 37.f, 37.f);
    }
    return _loadingView;
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
        
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr stopMonitoring];
    
    // 清缓存
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)initUI {
    
    [self setTitle:@"贷款合同" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    self.confirmBtn.backgroundColor = [MAIN_BLUE_COLOR colorWithAlphaComponent:.5f];
    self.confirmBtn.layer.cornerRadius = 22.f;
    self.confirmBtn.clipsToBounds = YES;
    self.confirmBtn.userInteractionEnabled = NO;
    
    [self.confirmBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self submitAction];
    }];
    
    self.webView = [[WKWebView alloc] init]; // 打开自适应 就要关掉这个alloc (重复了)
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    self.webView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - 58.f - UIDevice.safeDistanceBottom);
    
    [self.view addSubview:self.webView];
    
    [self getProtocol];
}

- (void)getProtocol {
    
    [MBManager showLoading];
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeConfirmContract) success:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        if (code == 200) {

            FPProtocolModel *model = list.firstObject;
            
            NSString *URLStr = [NSString stringWithFormat:@"%@?dataToken=%@&key=%@", model.address , FPUserModel.globalToken , self.keyContractWithTimestamp];
            
            NSURLRequest *request = [NSURLRequest requestWithURL:[self exchangePercentURLString:URLStr]];
            [self.webView loadRequest:request];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (void)submitAction {
    
    [MBManager showLoading];
    [FPLoanModel submitLoanWithParam:self.param success:^(NSInteger code, NSString * _Nonnull message) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            FPInreviewController *vc = [[FPInreviewController alloc] init];
            vc.bankCardInfo = self.bankCardInfo;
            vc.bankCardImgInfo = self.bankCardImgInfo;
            vc.amountInfo = self.amountInfo;
            [self.navigationController pushViewController:vc animated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:LoanApplySuccessNotification object:nil];
            
            [self signProtocolWithParams:[NSMutableArray arrayWithArray:self.protocolSource]];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    [self.loadingView startAnimating];
    NSLog(@"开始加载页面");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    self.confirmBtn.backgroundColor = MAIN_BLUE_COLOR;
    self.confirmBtn.userInteractionEnabled = YES;
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"页面加载完成");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"页面加载失败：%@", error.localizedDescription);
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"导航失败：%@", error.localizedDescription);
}

- (NSURL *)exchangePercentURLString:(NSString *)urlStr {
    
    NSMutableCharacterSet *set  = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [set addCharactersInString:@"#"];
    NSURL *URL = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:set]];
    
    return URL;
}


@end
